package edu.ajou.scw;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ProfileImage
 */
@WebServlet("/ProfileImage")
public class ProfileImage extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ProfileImage() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String id  = request.getParameter("id");
		
		DatabaseConnector conn = new DatabaseConnector();
		
		ArrayList<UserInfo> ui = conn.getUserInfo(id, true);
		
		if (ui != null && ui.size() > 0)
		{
			String fileName = ui.get(0).getImage();
			
			if (fileName != null)
			{
				String path = "/home/tomcat7/profile/" + fileName;
				File imgFile = new  File(path);
				try{
				   FileInputStream ifo = new FileInputStream(imgFile);
				   ByteArrayOutputStream baos = new ByteArrayOutputStream();
				   byte[] buf = new byte[1024];
				   int readlength = 0;
				   while( (readlength =ifo.read(buf)) != -1 )
				   {
				    baos.write(buf,0,readlength);
				   }
				   byte[] imgbuf = null;
				   imgbuf = baos.toByteArray();
				   baos.close();
				   ifo.close();    
				   
				   int length = imgbuf.length;   
				   OutputStream out = response.getOutputStream();    
				   out.write(imgbuf , 0, length);
				   out.close();   
				  }
				  catch(FileNotFoundException e)
				  {
				   
				  }
				  catch(IOException e)
				  {
				   
				  }
			}
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
